/**
 * vim: set ts=4 :
 * =============================================================================
 * SourceMod Sample Extension
 * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
 * =============================================================================
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, version 3.0, as published by the
 * Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * As a special exception, AlliedModders LLC gives you permission to link the
 * code of this program (as well as its derivative works) to "Half-Life 2," the
 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
 * by the Valve Corporation.  You must obey the GNU General Public License in
 * all respects for all other code used.  Additionally, AlliedModders LLC grants
 * this exception to all derivative works.  AlliedModders LLC defines further
 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
 * or <http://www.sourcemod.net/license.php>.
 *
 * Version: $Id$
 */

#include "extension.h"
#include "CDetour/detours.h"

/**
 * @file extension.cpp
 * @brief Implement extension code here.
 */

RconHook g_Interface;		/**< Global singleton for extension's main interface */

SMEXT_LINK(&g_Interface);


CDetour *detourCheckPassword = NULL;
CDetour *detourDataRequest = NULL;
//CDetour *detourLogCommand = NULL;
CDetour *detourIsPassword = NULL;


//Config:
IGameConfig *g_pGameConf = NULL;

//Forwards:
IForward *g_CheckPassword = NULL;
IForward *g_DataRequest = NULL;
//IForward *g_LogCommand = NULL;

netadr_s last_addr;

netadr_s& ListenerIDToAddress(CServerRemoteAccess *c, unsigned int id) //TODO: Replace with CUtlLinkedList usage
{
	
	//unsigned int pos = (id*8)-id;

	//netadr_s *addr;
	//void *pSomething = (void *)((intptr_t)c+0x28+pos*4);

	//netadr_s *addr = (netadr_s *)((intptr_t)pSomething+8);

	return c->m_Listeners[id]->addr;
}


DETOUR_DECL_MEMBER4(CServerRemoteAccess_WriteDataRequest_H, void, CRConServer*, conn, int, listener,const void*, pData, int, len )
{
	//(CRConServer *conn, unsigned int listener, const void *pData, int len)
	netadr_s addr = ListenerIDToAddress((CServerRemoteAccess *)this, listener);

	bf_read buffer(pData, 2048);


	//RCON_WriteDataRequest(id:number, request:number, data:string, ip:string, port:number) 
	cell_t Result = 0;
	g_DataRequest->PushCell(buffer.ReadLong()); //Id
	g_DataRequest->PushCell(buffer.ReadLong()); //Request

	char *str = buffer.ReadAndAllocateString();
	g_DataRequest->PushString(str); //Data
	
	g_DataRequest->PushString(addr.ToString(true)); //IP

	g_DataRequest->PushCell(addr.GetPort()); //Port

	g_DataRequest->Execute(&Result);
	delete str;

	if( Result == Pl_Continue || Result == 0 )
		DETOUR_MEMBER_CALL(CServerRemoteAccess_WriteDataRequest_H)( conn, listener, pData, len);
}

/*
DETOUR_DECL_MEMBER2(CServerRemoteAccess_LogCommand_H, void, unsigned int, listener, const char*, msg )
{
	//CServerRemoteAccess_LogCommand_H(unsigned int listener, const char *msg)
	netadr_s *addr = ListenerIDToAddress((CServerRemoteAccess *)this, listener);

	//RCON_LogCommand(msg:string, ip:string, port:number) 
	cell_t Result = 0;
	g_LogCommand->PushString(msg);  
	g_LogCommand->PushString(addr->ToString(true));
	g_LogCommand->PushCell(addr->GetPort());
	g_LogCommand->Execute(&Result);

	if( Result == Pl_Continue || Result == 0 )
		DETOUR_MEMBER_CALL(CServerRemoteAccess_LogCommand_H)(listener, msg);
}
*/


DETOUR_DECL_MEMBER1(CRConServer_IsPassword_H, bool, char*, password )
{
//bool CRConServer_IsPassword_H(const char *);
	if (&last_addr)
	{
		//RCON_CheckPassword(password:string, ip:string, port:number) 
		cell_t Result = 0;
		bool Access_bool = DETOUR_MEMBER_CALL(CRConServer_IsPassword_H)( password );
		cell_t Access = 0;
		
		if (Access_bool)
			Access = 1;

		g_CheckPassword->PushString(password);
		g_CheckPassword->PushCellByRef( &Access );
		g_CheckPassword->PushString(last_addr.ToString(true));
		g_CheckPassword->PushCell(last_addr.GetPort());
		g_CheckPassword->Execute(&Result);


		last_addr = NULL;
		if( Result == Pl_Continue || Result == 0 )
			return DETOUR_MEMBER_CALL(CRConServer_IsPassword_H)( password );
		else if( Access == 0 )
		{
			return false;
		}
		else
			return true;
		
	}
	
	return  DETOUR_MEMBER_CALL(CRConServer_IsPassword_H)( password );
}

DETOUR_DECL_MEMBER4( CServerRemoteAccess_CheckPassword_H, void, CRConServer*, conn,  unsigned int, listener, int, id, const char*, password )
{
	//void *CServerRemoteAccess_CheckPassword_H(CRConServer *, unsigned int, int, const char *);
	 last_addr = ListenerIDToAddress((CServerRemoteAccess *)this, listener);

      DETOUR_MEMBER_CALL(CServerRemoteAccess_CheckPassword_H)(conn, listener, id, password); 
}


bool RconHook::SDK_OnLoad(char *error, size_t maxlength, bool late)
{

	char conf_error[255] = "";
	if(!gameconfs->LoadGameConfigFile("rconhacks", &g_pGameConf, conf_error, sizeof(conf_error)))
	{
		if(conf_error[0])
			snprintf(error, maxlength, "Could not read rconhacks.txt: %s", conf_error);
		
		return false;
	}

	CDetourManager::Init(g_pSM->GetScriptingEngine(), g_pGameConf);

	// just use "library" "engine" instead of "library" "server"
	detourCheckPassword = DETOUR_CREATE_MEMBER(CServerRemoteAccess_CheckPassword_H, "RCON_CheckPassword");

	if (detourCheckPassword != NULL)
	{
		detourCheckPassword->EnableDetour();
	}
	else
	{
		g_pSM->LogError(myself, "Sigscan for RCON_CheckPassword failed.");	
		return false;
	}

	detourDataRequest = DETOUR_CREATE_MEMBER(CServerRemoteAccess_WriteDataRequest_H, "RCON_DataRequest");

	if (detourDataRequest != NULL)
	{
		detourDataRequest->EnableDetour();
	}
	else
	{
		g_pSM->LogError(myself, "Sigscan for RCON_DataRequest failed.");	
		return false;
	}

	
	/*detourLogCommand = DETOUR_CREATE_MEMBER(CServerRemoteAccess_LogCommand_H, "RCON_LogCommand");

	if (detourLogCommand != NULL)
	{
		detourLogCommand->EnableDetour();
	}
	else
	{
		g_pSM->LogError(myself, "Sigscan for RCON_LogCommand failed.");	
		return false;
	}
	*/

	detourIsPassword = DETOUR_CREATE_MEMBER(CRConServer_IsPassword_H, "RCON_IsPassword");

	if (detourIsPassword != NULL)
	{
		detourIsPassword->EnableDetour();
	}
	else
	{
		g_pSM->LogError(myself, "Sigscan for RCON_IsPassword failed.");	
		return false;
	}
	return true;
	
}

void RconHook::SDK_OnAllLoaded()
{
	g_CheckPassword = forwards->CreateForward("OnRconCheckPassword", ET_Hook, 4, NULL, Param_String, Param_CellByRef, Param_String, Param_Cell );
	g_DataRequest = forwards->CreateForward("OnWriteDataRequest", ET_Hook, 5, NULL, Param_Cell, Param_Cell, Param_String, Param_String, Param_Cell );
	//g_LogCommand = forwards->CreateForward("OnLogRcon", ET_Hook, 3, NULL, Param_String, Param_String, Param_Cell );
}

void RconHook::SDK_OnUnload()
{
	if (detourCheckPassword != NULL)
	{
		detourCheckPassword->Destroy();
		detourCheckPassword = NULL;
	}
	if (detourDataRequest != NULL)
	{
		detourDataRequest->Destroy();
		detourDataRequest = NULL;
	}
	//if (detourLogCommand != NULL)
	//{
	//	detourLogCommand->Destroy();
	//	detourLogCommand = NULL;
	//}
	if (detourIsPassword != NULL)
	{
		detourIsPassword->Destroy();
		detourIsPassword = NULL;
	}
	gameconfs->CloseGameConfigFile(g_pGameConf);

	forwards->ReleaseForward(g_CheckPassword);
	forwards->ReleaseForward(g_DataRequest);
	/*forwards->ReleaseForward(g_LogCommand);;*/
}


